package cn.virens.common.spring;

import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.classloader.ClassLoaderUtil;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;

public class ResourceUtil {
    public static Resource getResource(String location) throws IOException {
        return resolver().getResource(location);
    }

    public static Resource safeResource(String location) throws IOException {
        Resource res = getResource(location);
        if (res != null && res.exists()) {
            return res;
        }

        return null;
    }

    public static Resource[] getResources(String locationPattern) throws IOException {
        return resolver().getResources(locationPattern);
    }

    public static Resource[] safeResources(String locationPattern) throws IOException {
        return ArrayUtil.filter(getResources(locationPattern), res -> {
            return res != null && res.exists();
        });
    }

    public static PathMatchingResourcePatternResolver resolver() throws IOException {
        return new PathMatchingResourcePatternResolver(ClassLoaderUtil.getClassLoader());
    }
}
